package logic

import (
	"context"
	"fmt"
	"module-name/models/cache"
	"module-name/modulerpc/internal/svc"
	"module-name/modulerpc/modulerpc"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopCarListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopCarListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopCarListLogic {
	return &ShopCarListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShopCarListLogic) ShopCarList(in *modulerpc.ShopCarListRequest) (*modulerpc.ShopCarListResponse, error) {
	// todo: add your logic here and delete this line
	var shop []*modulerpc.ShopCarList
	key := fmt.Sprintf("shopcar_%d:*", in.UserId)
	keys, _ := cache.Rdb.Keys(cache.Ctx, key).Result()
	for _, k := range keys {
		promap, _ := cache.Rdb.HGetAll(cache.Ctx, k).Result()
		userId, _ := strconv.Atoi(promap["UserId"])
		proId, _ := strconv.Atoi(promap["ProductId"])
		name := promap["Name"]
		price, _ := strconv.ParseFloat(promap["Price"], 64)
		stock, _ := strconv.Atoi(promap["Stock"])
		list := modulerpc.ShopCarList{
			UserId: int64(userId),
			ProId:  int64(proId),
			Name:   name,
			Price:  float32(price),
			Stock:  int64(stock),
		}
		shop = append(shop, &list)
	}
	return &modulerpc.ShopCarListResponse{List: shop}, nil
}
